package com.dong.thread.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 曾经的面试题：（淘宝？）
 * 实现一个容器，提供两个方法，add，size
 * 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 *
 * 自己思考：用CyclicBarrier实现
 *
 * @author by jiweidong on 2021/11/28.
 */
public class T10_Interview_01_CyclicBarrier {

    List<Object> list = new ArrayList<>();

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    static Thread t2;
    static Thread t1;

    public static void main(String[] args) {

        T10_Interview_01_CyclicBarrier list = new T10_Interview_01_CyclicBarrier();

        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

        t1 = new Thread(() -> {
            System.out.println("t1 started");
            for (int i = 0; i < 10; i++) {
                list.add(i);
                System.out.println("t1 add " + i);
                if (list.size() == 5) {
                    try {
                        cyclicBarrier.await();
                        t2.join();
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        });

        t2 = new Thread(() -> {
            System.out.println("t2 started");
            try {
                System.out.println("t2 observing...");
                cyclicBarrier.await();
                System.out.println("t2 observed added 5, t2 end.");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        t2.start();
        t1.start();

    }

}
